#include <cpcap-capture-devices.hpp>
#include <linux-fcn.hpp>

#ifdef LINUX
#ifdef DEBUG
#define DUMP_FOURCC(x) (x) & 0xFF, ((x) >> 8) & 0xFF, ((x) >> 16) & 0xFF, ((x) >> 24) & 0xFF
#endif

int
xioctl(int fd, int request, void *arg)
{
    int result;

    do {
        result = ioctl(fd, request, arg);
    } while (result == -1 && errno == EINTR);

    return result;
}

#ifdef DEBUG
void
debug_dump_format(v4l2_format fmt)
{
    const char *field[10] = {"Any",
                             "None",
                             "Top",
                             "Bottom",
                             "Interlaced",
                             "Seq_TB",
                             "Seq_BT",
                             "Alternate",
                             "Interlaced TB",
                             "Interlaced BT"
                            };
    fprintf(stderr, "* Formato establecido :\n");
    fprintf(stderr, "\tFOURCC     = %c%c%c%c\n", DUMP_FOURCC(fmt.fmt.pix.pixelformat));
    fprintf(stderr, "\tResolucion = %dx%d\n", fmt.fmt.pix.width, fmt.fmt.pix.height);
    fprintf(stderr, "\tLongitud   = %d bytes\n", fmt.fmt.pix.sizeimage);
    fprintf(stderr, "\tCampo      = %s\n", field[fmt.fmt.pix.field]);
}

void
debug_dump_formats(FormatsInfo *formats, int count)
{
    int i;
    int j;
    int k;

    for (i = 0 ; i < count ; i++) {
        const char *fmt;

        fmt = "* Format[%d] : %-30s [%c%c%c%c]\n";
        fprintf(stderr, fmt, i, formats[i].description, DUMP_FOURCC(formats[i].fmt));
        for (j = 0 ; j < formats[i].sizes_count ; j++) {
            FormatSize fmtsize;

            fmtsize = formats[i].sizes[j];
            fmt     = "\t<*> Size[%d] = %dx%d\n";

            fprintf(stderr, fmt, i, fmtsize.width, fmtsize.height);
            for (k = 0 ; k < fmtsize.fps_count ; k++) {
                float   fps;
                fps = (float)fmtsize.fps_numerator[k] /\
                      (float)fmtsize.fps_denominator[k];
                fmt = "\t\t-frame rate[%d] -> %.4ffps\n";
                fprintf(stderr, fmt, k, fps);
            }
        }
    }
}

void
debug_dump_inputs(PhysicalInput *inputs, int count, int connected_type)
{
    int     i;

    fprintf(stderr, "* %d tipos de entrada FISICA encontrados\n", count);
    for (i = 0 ; i < count ; i++) {
        fprintf(stderr, "\t%-20s ", inputs[i].name);
        if (connected_type == i)
            fprintf(stderr, "[+]\n");
        else
            fprintf(stderr, "[-]\n");
    }
}
#endif
#endif
